package org.ftc.security;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.ftc.service.LoadUserDataTaskService;
import org.ftc.service.RoleAuthService;
import org.ftc.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class SecurityManager implements UserDetailsService {

	@Autowired
	private UsersService usersService;
	@Autowired
	private LoadUserDataTaskService loadService;
	@Autowired
	RoleAuthService roleAuthService;

	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
//		if(StringUtils.equals(userName, "xxxxxx")){
//			List<GrantedAuthority> authSet = new ArrayList<GrantedAuthority>();
//			authSet.add(new SimpleGrantedAuthority("HOME"));
//				RoleAuth roleAuth = roleAuthService.get("00000000");
//				if (roleAuth != null) {
//					for (String auth : roleAuth.getAuths().split(",")) {
//						authSet.add(new SimpleGrantedAuthority(auth));
//					}
//				}
//			User user = new User(userName, null, true, "00000000", authSet);
//			Authentication authentication = new UsernamePasswordAuthenticationToken(user, null,
//					authSet);
//				SecurityContextHolder.getContext().setAuthentication(authentication);
//				return user;
//		}
		
		User user = usersService.loginUserName(userName);
		return user;
		
		// throw new UsernameNotFoundException("User " + userName +
		// " has no GrantedAuthority");
//		List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRole());
//		 
//		return buildUserForAuthentication(user, authorities);
		
	}
	
//	private org.springframework.security.core.userdetails.User buildUserForAuthentication(org.springframework.security.core.userdetails.User user, 
//			List<GrantedAuthority> authorities) {
//			return new org.springframework.security.core.userdetails.User(user.getUsername(), 
//				user.getPassword(), user.isEnabled(), 
//	                        true, true, true, authorities);
//		}
//	 
//		private List<GrantedAuthority> buildUserAuthority(Set<User> userRoles) {
//	 
//			Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
//	 
//			// Build user's authorities
//			for (User userRole : userRoles) {
//				setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
//			}
//	 
//			List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
//	 
//			return Result;
//		}
}
